<template>
  <div class="relative w-full h-full pb60">
    <div class="border-bottom mb12">
      <PageHeader :title="id ? $t('couponManagement.editCoupon') : $t('couponManagement.addNewCoupon')">
        <template #right>
          <el-button type="primary" @click="goBack" size="small">
            <SvgIcon name="iconfanhui" color="#fff" class="mr4" />
            {{ $t('couponManagement.backToPage') }}
          </el-button>
        </template>
      </PageHeader>
    </div>

    <el-form ref="formRef" :model="form" :rules="rules" label-width="200px">
      <div class="titleRow pl10">{{ $t('couponManagement.basicInfo') }}</div>

      <el-form-item :label="$t('couponManagement.couponName')" prop="name">
        <el-input
          v-model="form.name"
          maxlength="20"
          show-word-limit
          style="width: 320px"
        />
      </el-form-item>

      <el-form-item :label="$t('couponManagement.total')" prop="total">
        <div>
          <el-input-number
            v-model="form.total"
            controls-position="right"
            :min="0"
            :max="100000000"
            style="width: 320px"
          />
          <div class="tip-text">{{ $t('couponManagement.totalTip') }}</div>
        </div>
      </el-form-item>

      <el-form-item :label="$t('couponManagement.stackWithStoreCoupon')" prop="canStack">
        <el-radio-group v-model="form.canStack">
          <el-radio :label="1">{{ $t('couponManagement.allow') }}</el-radio>
          <el-radio :label="0">{{ $t('couponManagement.notAllow') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('couponManagement.applicableProducts')" prop="applicableType">
        <div>
          <el-radio-group
            v-model="form.applicableType"
            @change="handleApplicableTypeChange"
          >
            <el-radio :label="1">{{ $t('couponManagement.allProducts') }}</el-radio>
            <el-radio :label="2">{{ $t('couponManagement.specificCategories') }}</el-radio>
          </el-radio-group>

          <el-form-item
            v-if="form.applicableType === 2"
            prop="categoryIds"
            label=""
            :rules="[
              { required: true, message: $t('couponManagement.pleaseSelectCategory'), trigger: 'change' },
            ]"
          >
            <el-tree
              ref="treeRef"
              :data="categoryTree"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              style="
                height: 300px;
                overflow-y: auto;
                margin-top: 10px;
                border: 1px solid #dcdfe6;
                padding: 10px 32px 10px 10px;
              "
              @check="handleCheckChange"
            />
          </el-form-item>
        </div>
      </el-form-item>

      <el-form-item :label="$t('couponManagement.collectionMethod')" prop="getType">
        <div>
          <el-radio-group v-model="form.getType">
            <el-radio :label="1">{{ $t('couponManagement.freeCollection') }}</el-radio>
          </el-radio-group>
          <div class="tip-text">{{ $t('couponManagement.collectionMethodTip') }}</div>
        </div>
      </el-form-item>

      <el-form-item :label="$t('couponManagement.activityTime')" prop="activityTime">
        <el-date-picker
          v-model="form.activityTime"
          type="datetimerange"
          :range-separator="$t('datePick.至')"
          :start-placeholder="$t('couponManagement.startDate')"
          :end-placeholder="$t('couponManagement.endDate')"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 400px"
          class="flex-grow-0"
        />
      </el-form-item>

      <el-form-item :label="$t('couponManagement.useTime')" prop="useTime">
        <el-date-picker
          v-model="form.useTime"
          type="datetimerange"
          :range-separator="$t('datePick.至')"
          :start-placeholder="$t('couponManagement.startDate')"
          :end-placeholder="$t('couponManagement.endDate')"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 400px"
          class="flex-grow-0"
        />
      </el-form-item>

      <!-- <el-form-item label="使用门槛" prop="threshold">
        <div>
          <div class="flex_aic">
            <span>订单满</span>
            <el-input-number
              v-model="form.threshold"
              controls-position="right"
              :min="0"
              style="width: 200px; margin: 0 10px"
            />
            <span>元</span>
          </div>
          <div class="tip-text">
            订单满多少元时可以使用此优惠券，0元代表无使用门槛
          </div>
        </div>
      </el-form-item> -->

      <el-form-item :label="$t('couponManagement.couponType')" prop="couponType">
        <el-radio-group v-model="form.couponType">
          <el-radio :label="1">{{ $t('couponManagement.discountCoupon') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('couponManagement.discountContent')" prop="amount">
        <div class="flex_aic">
          <span>{{ $t('couponManagement.reduce') }}</span>
          <el-input-number
            v-model="form.amount"
            controls-position="right"
            :min="0"
            style="width: 200px; margin: 0 10px"
          />
          <span>{{ $t('couponManagement.yuan') }}</span>
        </div>
      </el-form-item>

      <div class="titleRow pl10 mt15 mb15">{{ $t('couponManagement.collectionRules') }}</div>

      <el-form-item :label="$t('couponManagement.limitPerPerson')" prop="limitTimes">
        <div>
          <el-input-number
            v-model="form.limitTimes"
            controls-position="right"
            :min="0"
            style="width: 320px"
          />
          <div class="tip-text">{{ $t('couponManagement.limitPerPersonTip') }}</div>
        </div>
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <div class="fixed-bottom">
      <el-button @click="goBack">{{ $t('couponManagement.back') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('couponManagement.save') }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const formRef = ref(null);
const id = ref(route.query.id);

const form = ref({
  name: "",
  total: 0,
  canStack: 1,
  applicableType: 1,
  getType: 1,
  activityTime: [],
  useTime: [],
  threshold: 0,
  couponType: 1,
  amount: 0,
  limitTimes: 0,
  categoryIds: [],
});

const rules = {
  name: [
    { required: true, message: t('couponManagement.pleaseEnterCouponName'), trigger: "blur" },
    { max: 20, message: t('common.maxLength', { length: 20 }), trigger: "blur" },
  ],
  total: [{ required: true, message: t('common.required'), trigger: "blur" }],
  canStack: [{ required: true, message: t('common.required'), trigger: "change" }],
  applicableType: [{ required: true, message: t('common.required'), trigger: "change" }],
  getType: [{ required: true, message: t('common.required'), trigger: "change" }],
  activityTime: [{ required: true, message: t('common.required'), trigger: "change" }],
  useTime: [{ required: true, message: t('common.required'), trigger: "change" }],
  // threshold: [{ required: true, message: "请输入使用门槛", trigger: "blur" }],
  couponType: [{ required: true, message: t('common.required'), trigger: "change" }],
  amount: [{ required: true, message: t('common.required'), trigger: "blur" }],
  limitTimes: [{ required: true, message: t('common.required'), trigger: "blur" }],
  categoryIds: [{ required: true, message: t('couponManagement.pleaseSelectCategory'), trigger: "change" }],
};

const goBack = () => {
  router.back();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid) => {
    if (valid) {
      console.log("提交表单", form.value);
      // 这里添加提交逻辑
    }
  });
};

const categoryTree = ref([
  {
    id: 1,
    label: "数码产品",
    children: [
      { id: 11, label: "手机" },
      { id: 12, label: "平板电脑" },
      { id: 13, label: "笔记本电脑" },
    ],
  },
  {
    id: 2,
    label: "服装服饰",
    children: [
      { id: 21, label: "男装" },
      { id: 22, label: "女装" },
      { id: 23, label: "童装" },
    ],
  },
  {
    id: 3,
    label: "家用电器",
    children: [
      { id: 31, label: "大家电" },
      { id: 32, label: "小家电" },
      { id: 33, label: "厨房电器" },
    ],
  },
  {
    id: 4,
    label: "美妆护肤",
    children: [
      { id: 41, label: "面部护理" },
      { id: 42, label: "彩妆" },
      { id: 43, label: "香水" },
    ],
  },
]);

const defaultProps = {
  children: "children",
  label: "label",
};

const treeRef = ref(null);

const handleApplicableTypeChange = (val) => {
  if (val === 1) {
    form.value.categoryIds = [];
  }
};

const handleCheckChange = (data, checked) => {
  form.value.categoryIds = checked.checkedKeys;
};

watch(
  () => form.value.applicableType,
  (newVal) => {
    if (newVal === 1) {
      formRef.value?.clearValidate(["categoryIds"]);
    }
  }
);
</script>

<style lang="scss" scoped>
.border-bottom {
  width: 100%;
  border-bottom: 1px solid #e5e5e5;
}

.titleRow {
  width: 100%;
  height: 36px;
  border-radius: 2px;
  background: #fffaf7;
  line-height: 36px;
}

.tip-text {
  font-size: 12px;
  color: #00000073;
  margin-top: 4px;
  line-height: 12px;
}

.fixed-bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 0;
  text-align: center;
  background: #fff;
  border-top: 1px solid #e5e5e5;
}

.pb60 {
  padding-bottom: 60px;
}

:deep(.el-form-item__label) {
  &:before {
    content: "*";
    color: #ff4d4f;
  }
}
:deep(.el-tree) {
  .el-tree-node__content {
    height: 32px;
  }
}
</style>
